package org.spamforces.web.frame;

import org.nocturne.annotation.Parameter;
import org.nocturne.link.Links;
import org.nocturne.main.ApplicationContext;
import org.nocturne.main.Page;
import org.spamforces.web.page.DashboardPage;
import org.spamforces.web.page.RecipientProvidersManagePage;
import org.spamforces.web.page.WebPage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Mike Mirzayanov
 */
public class Menu extends ApplicationFrame {
    @Parameter
    private long contestId;

    @Override
    public void action() {
        Page page = ApplicationContext.getInstance().getCurrentPage();

        if (page instanceof WebPage) {
            WebPage appPage = (WebPage) page;

            Link[] links;

            if (appPage.isAnonymousAccessAllowed()) {
                links = getAnonymousLinks();
            } else {
                links = getAuthorizedLinks();
            }

            setupActive(links);
            put("links", links);
        }
    }

    private String getPageUrl() {
        return getRequest().getRequestURI().substring(
                getRequest().getContextPath().length());
    }

    private void setupActive(Link[] links) {
        String[] tokens = getPageUrl().split("[^\\w]+");
        String path = null;
        for (String token : tokens) {
            if (!token.isEmpty()) {
                path = token;
            }
        }
        for (Link link : links) {
            link.setActive(link.isActiveForUrl(path));
        }
    }

    @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"})
    private Link[] getAuthorizedLinks() {
        List<Link> links = new ArrayList<>();

        links.addAll(Arrays.asList(
                new Link(Links.getLink(RecipientProvidersManagePage.class), "Providers"),
                new Link(Links.getLink(DashboardPage.class), "Broadcasts")
        ));

        return links.toArray(new Link[]{});
    }

    private Link[] getAnonymousLinks() {
        List<Link> links = new ArrayList<>();

        links.addAll(Arrays.asList(new Link("", "Login")));

        return links.toArray(new Link[]{});
    }

    public static class Link {
        private String url;
        private String text;
        private boolean active;

        private Link(String url, String text) {
            this.url = url;
            this.text = text;
        }

        public String getUrl() {
            return url;
        }

        public String getText() {
            return text;
        }

        public void setActive(boolean active) {
            this.active = active;
        }

        public boolean isActive() {
            return active;
        }

        public boolean isActiveForUrl(String url) {
            return this.url != null && this.url.equals(url);
        }
    }
}
